import { Request, Response } from 'express';
import { MpWeixinService } from './MpWeixinService';
import { Gender } from '../../entities/User';

const mpWeixinService = new MpWeixinService();

/**
 * 微信小程序登录/注册二合一接口
 * 如果用户不存在，则自动注册
 */
export const mpLoginOrRegister = async (req: Request, res: Response) => {
  try {
    const { code, nickName, avatarUrl, gender: wxGender } = req.body;
    
    if (!code) {
      return res.json({
        success: false,
        message: '缺少登录code'
      });
    }

    // 先尝试登录
    const wxLoginResult = await mpWeixinService.login(code);
    
    // 如果用户已注册，直接返回登录结果
    if (wxLoginResult.isRegistered) {
      return res.json({
        success: true,
        data: wxLoginResult,
        message: '登录成功'
      });
    }
    
    // 用户不存在，进行自动注册
    // 将微信性别转换为系统性别枚举
    const userGender = wxGender === 1 ? Gender.MALE : Gender.FEMALE;
    
    // 构建简化的注册参数，确保所有必要字段都有值
    const registerParams = {
      name: nickName || '微信用户', // 默认使用昵称作为姓名
      nickname: nickName || '',
      avatar: avatarUrl || '',
      gender: userGender,
      openId: wxLoginResult.openid || '',
      // 以下是必填字段，但用户首次登录时没有，使用默认值或空值
      idCard: '', // 后续用户可以补充
      mobile: '', // 后续用户可以补充
      address: '', // 确保 address 有默认值
      permanentAddress: '', // 确保 permanentAddress 有默认值
      birthday: '2000-01-01', // 默认生日
      verifyCode: '000000' // 自动注册跳过验证码验证
    };
    
    // 调用自动注册方法
    const { user, token } = await mpWeixinService.autoRegister(registerParams);
    
    return res.json({
      success: true,
      data: {
        ...user,
        token,
        isNewUser: true // 标记为新注册用户
      },
      message: '自动注册成功'
    });
  } catch (error: any) {
    res.json({
      success: false,
      message: error.message || '登录/注册失败'
    });
  }
};

/**
 * 获取手机号
 */
export const getPhoneNumber = async (req: Request, res: Response) => {
  try {
    const { sessionKey, encryptedData, iv } = req.body;

    if (!sessionKey || !encryptedData || !iv) {
      return res.json({
        success: false,
        message: '参数不完整'
      });
    }

    const phoneInfo = await mpWeixinService.decryptPhoneNumber(
      sessionKey,
      encryptedData,
      iv
    );

    res.json({
      success: true,
      data: phoneInfo
    });
  } catch (error: any) {
   res.json({
      success: false,
      message: error.message || '获取手机号失败'
    });
  }
};

/**
 * 更新用户信息
 * 用于用户补充个人信息
 */
export const updateUserInfo = async (req: Request, res: Response) => {
  try {
    const { userId, mobile, idCard, name, address, permanentAddress } = req.body;
    
    if (!userId) {
      return res.json({
        success: false,
        message: '缺少用户ID'
      });
    }

    const result = await mpWeixinService.updateUserInfo(userId, {
      mobile,
      idCard,
      name,
      address,
      permanentAddress
    });
    
    res.json({
      success: true,
      data: result,
      message: '用户信息更新成功'
    });
  } catch (error: any) {
   res.json({
      success: false,
      message: error.message || '更新用户信息失败'
    });
  }
};

/**
 * 刷新用户token
 */
export const refreshToken = async (req: Request, res: Response) => {
  try {
    const { userId } = req.body;
    
    if (!userId) {
      return res.json({
        success: false,
        message: '缺少用户ID'
      });
    }

    const result = await mpWeixinService.refreshToken(userId);
    
    res.json({
      success: true,
      data: result,
      message: '刷新token成功'
    });
  } catch (error: any) {
   res.json({
      success: false,
      message: error.message || '刷新token失败'
    });
  }
};